<template>
  <div id="sharePage">
    <el-dialog
      id="sharePageDialog"
      :title="shareTitle"
      :show-close="false"
      :visible.sync="shareVisibleFun"
      @close="destroyshare"
      width="66%"
    >
      <el-tabs v-model="activeName" @tab-click="shareHandleClick">
        <el-tab-pane label="同事分享" name="first">
          <el-container style="height: 357px; border: 1px solid #eee">
            <el-aside width="200px" style="background-color: #f5f5f5">
              <el-tree
                :data="workmates"
                show-checkbox
                node-key="id"
                v-if="isRouterAlive"
                @check="handleWorkmateCheck"
                ref="workmatetree"
                highlight-current
                :props="defaultProps"
              ></el-tree>
              <!-- @node-expand="handleWorkmateExp" -->
            </el-aside>
            <!-- <el-header style="text-align: right; font-size: 12px">el-header</el-header> -->
            <el-container>
              <el-table
                :data="checkedWorkmate"
                height="300"
                style="text-align:center"
                empty-text="尚未选择"
              >
                <el-table-column property="department" label="部门"></el-table-column>
                <el-table-column property="job" label="职位"></el-table-column>
                <el-table-column property="name" label="姓名"></el-table-column>
                <el-table-column label="移除选择">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click.native.prevent="deleteRow(scope.$index, checkedWorkmate,scope.row)"
                    >
                      <i class="el-icon-delete"></i>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-footer>
                <span class="has-checked">{{haschecked}}</span>
              </el-footer>
            </el-container>
          </el-container>
        </el-tab-pane>
        <el-tab-pane label="群组分享" name="second">
          <el-container style="height: 357px; border: 1px solid #eee">
            <el-aside width="200px" style="background-color: #f5f5f5">
              <el-tree
                :data="groups"
                ref="grouptree"
                show-checkbox
                node-key="key"
                @check="handleGroupCheck"
                highlight-current
                :props="defaultProps"
              ></el-tree>
              <!-- @node-expand="handleWorkmateExp" -->
            </el-aside>
            <!-- <el-header style="text-align: right; font-size: 12px">el-header</el-header> -->
            <el-container>
              <el-table
                :data="checkedGroup"
                height="300"
                style="text-align:center"
                empty-text="尚未选择"
              >
                <el-table-column property="id" label="id"></el-table-column>
                <el-table-column property="name" label="群组名称"></el-table-column>
                <el-table-column property="permission" label="权限"></el-table-column>
                <el-table-column label="移除选择">
                  <template slot-scope="scope1">
                    <el-button
                      size="mini"
                      @click.native.prevent="deleteRow(scope1.$index,checkedGroup,scope1.row)"
                    >
                      <i class="el-icon-delete"></i>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-footer>
                <span class="has-checked">{{ischecked}}</span>
              </el-footer>
            </el-container>
          </el-container>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="destroyshare">取 消</el-button>
        <el-button type="primary" @click="submitShareFunc()">分 享</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ["sharePara", "shareTitle",'companyList'],
  data() {
    return {
      shareVisibleFun:false,
      shareGroupList: [],
      activeName: "first",
      groups: [
        {
          label: "我管理的群组",
          children: [],
          floor: [1]
        },
        { label: "我参加的群组", children: [], floor: [1] }
      ],
      checkedGroup: [],
      workmates: [],
      deExpWorkmate: [],
      isRouterAlive: true,
      istree: false,
      checkedWorkmate: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      percentComplete:0,
    };
  },
  computed: {
    haschecked: function() {
      if (this.checkedWorkmate != false) {
        return "当前已选择" + this.checkedWorkmate.length + "人";
      } else {
        return "";
      }
    },
    ischecked: function() {
      if (this.checkedGroup != false) {
        return "当前已选择" + this.checkedGroup.length + "个群组";
      } else {
        return "";
      }
    },
  },
  watch: {
    istree: function(newVal, oldVal) {
      console.log(newVal);
      if (newVal == true) {
        this.getWorkmateAuto(this.workmates,3,'');
      }
    },
  },
  created() {
    // this.getOrganizeOwn();
    this.initDepartment();
    this.groupList();
  },
  mounted() {
    console.log(this.companyList);
  },
  methods: {
    destroyshare() {
      this.$emit("noclickshare");
      this.$refs.workmatetree.setCheckedKeys([]);
      this.$refs.grouptree.setCheckedKeys([]);
      this.checkedWorkmate = [];
      this.checkedGroup = [];
      this.isRouterAlive = false;
        this.$nextTick(function() {
          this.isRouterAlive = true;
        });
      this.shareVisibleFun = false;
    },
    alertSuccess(msg) {
      this.$message({
        message: msg,
        type: "success"
      });
    },
    alertLose(msg) {
      this.$message.error(msg);
    },
    handleChange(value, direction, movedKeys) {
      // console.log(value, direction, movedKeys);
    },
    filterMethod(query, item) {
      return item.pinyin.indexOf(query) > -1;
    },
    shareHandleClick(tab, event) {
      // console.log(tab, event, index);
    },
    groupList() {
      let para = { params: { groupName: "" } };
      this.$http.get("/groupInfo/list", para).then(
        res => {
          let { data } = res;
          if (data !== false) {
            data.forEach(item => {
              if (item.isOwner == 1) {
                this.groups[0].children.push({
                  key: item.groupId,
                  label: item.groupName,
                  owner: "管理员",
                  floor: 2
                });
              } else {
                this.groups[1].children.push({
                  key: item.groupId,
                  label: item.groupName,
                  owner: "普通成员",
                  floor: 2
                });
              }
            });
          } else {
            this.$message({
              message: "暂无群组!!",
              type: "info"
            });
          }
        },
        err => {
          this.$message({
            message: "网络出错!!",
            type: "error"
          });
        }
      );
    },
    handleGroupCheck(current, total) {
      this.checkedGroup = [];
      console.log(total)
      if (total.checkedNodes.length > 0) {
        total.checkedNodes.forEach(val => {
          if (val.floor == 2) {
            this.checkedGroup.push({
              id: val.key,
              name: val.label,
              permission: val.owner,
              nodedata: val
            });
          }
        });
      }
      console.log(current);
      console.log(total);
    },
    getWorkmateAuto(arr,a,cname) {
      arr.forEach(val => {
        let dlabel = val.label;
        val.children.forEach(v => {
          let jlabel = v.label;
          v.children = [];
          this.getworkmate(v.children, v.id, jlabel, dlabel,a,cname);
        });
      });
    },
    deleteRow(index, rows, row) {
      if (this.activeName == "first") {
        this.$refs.workmatetree.setChecked(row.nodedata);
      } else if(this.activeName=="second"){
        this.$refs.grouptree.setChecked(row.nodedata);
      }
      rows.splice(index, 1);
    },
    initDepartment() {
      this.$http.get("/user/getOrganizeOwn").then(
        res => {
            let { data } = res;
            this.workmates = [];
            if (res.status == 200 && res.data != false) {
              data.forEach(item => {
                let children = [];
                if (item.positionList != false) {
                  item.positionList.forEach(item1 => {
                    children.push({
                      label: item1.posttionName,
                      id: item1.positionId,
                      floor: 2,
                      children: []
                    });
                  });
                }
                let ischecked=false
                if(children==false){
                  ischecked=true
                }
                this.workmates.push({
                  label: item.departmentName,
                  id: item.departmentId,
                  job: item.positionList,
                  floor: 1,
                  children: children || [],
                  disabled:ischecked
                });
              });
              this.istree = true;
            }
        },
        err => {
          this.$message({
            message: "网络出错!!",
            type: "error"
          });
        }
      );
    },
    handleWorkmateCheck(current, total) {
      this.checkedWorkmate = [];
      if (total.checkedNodes.length > 0) {
        total.checkedNodes.forEach(val => {
          if (val.floor == 3) {
            this.checkedWorkmate.push({
              department: val.dlabel,
              job: val.jlabel,
              name: val.label,
              id: val.id,
              nodedata: val
            });
          }
        });
      }
    },
    // handleWorkmateExp(data, node, current) {
    //   console.log(node);
    //   console.log(data);
    //   if (data.floor == 1 && data.children != false) {
    //     data.children.forEach(item => {
    //       item.children = [];
    //       this.getworkmate(item.children, item.id);
    //     });
    //   }
    // },
    getworkmate(children, id, jlabel, dlabel,a,cname) {
      this.$http
        .get("/user/getUserOrganize", {
          params: {
            positionId: id
          }
        })
        .then(res => {
          let { data } = res;
          if (res.status == 200 && data != false) {
            data.forEach(item => {
              children.push({
                cname:cname,
                dlabel: dlabel,
                jlabel: jlabel,
                label: item.realName,
                id: item.id,
                floor: a,
                userEmail: item.userEmail
              });
              //   this.$refs.tree.setCheckedKeys([item.id]);
            });
            this.isRouterAlive = false;
        this.$nextTick(function() {
          this.isRouterAlive = true;
        });
          }
        });
    },
    groupInfo() {
      let userIdList = [];
      if (this.checkedGroup.length == 0) {
        this.alertLose("请选择要分享至的群组");
        return;
      } else {
        this.checkedGroup.forEach(val => {
          userIdList.push(val.id);
        });
      }
      let para = { groupStr: userIdList, fileId: this.sharePara[0].id };
      this.$http.post("/groupInfo/saveGroupFile", para).then(
        res => {
          let { msg, status } = res;
          if (status == 200 && msg === "分享成功") {
            this.$message({ message: "分享成功!", type: "success" });
            this.destroyshare()
          } else {
            this.$message({ message: msg, type: "error" });
          }
        },
        err => {
          this.$message({
            message: "网络出错!!",
            type: "error"
          });
        }
      );
    },
    submitShareFunc() {
      console.log(this.activeName);
      if (this.activeName == "second") {
        this.groupInfo();
      } else if (this.activeName == "first") {
        this.shareToWorkmate();
      }
    },
    shareToWorkmate() {
      let fileId = this.sharePara[0].id;
      let userIdList = [];
      if (this.checkedWorkmate.length == 0) {
        this.alertLose("请选择要分享至的同事");
        return;
      } else {
        this.checkedWorkmate.forEach(val => {
          userIdList.push(val.id);
        });
      }
      let para = {
        acceptUserId: userIdList,
        fileId: fileId
      };
      this.$http.post("/share/send", para).then(
        res => {
          if (res.status == 200) {
            this.alertSuccess("分享成功");
            this.destroyshare()
          } else if (res.msg == "以上用户已共享过此文件,请重新选择分享用户！") {
            let namelist = "";
            res.data.forEach(name => {
              namelist = namelist + name + ",";
            });
            this.alertLose(namelist + "已共享过此文件，请注意本次未给他们分享");
            this.destroyshare()
          } else {
            this.alertLose("分享失败");
          }
          console.log(res);
        },
        err => {
          this.$message({
            message: "网络出错!!",
            type: "error"
          });
        }
      );
    },
    // getOrganizeOwn() {
    //   this.$http.get("/user/getOrganizeOwn").then(
    //     res => {
    //       let { msg, status, data } = res;
    //       // console.log("getOrganizeOwn", res);
    //     },
    //     err => {
    //       this.$message({
    //         message: "网络出错!!",
    //         type: "error"
    //       });
    //     }
    //   );
    // }
  }
};
</script>

<style scoped lang="scss">
#sharePage {
  .has-checked {
    position: absolute;
    bottom: 20px;
    width: 300px;
    text-align: center;
    left: 50%;
    transform: translateX(-50%);
  }
  .el-header {
    background-color: #b3c0d1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }
}
</style>

